#!/bin/bash

. $OPENARS_HOME/common/debug.h
. $OPENARS_HOME/common/functions.h

user=$USER_ARS
[ -z "$user" ] && user=$LOGNAME

:>$OUTFILE

# $OUTFILE --> CMDB
function update_db() {
if [ -z "$CONNECT_ARS" ]; then
    ERR "not defined CONNECT_ARS environment for Oracle connect. exit."
    exit 1;
fi
$ORACLE_HOME/bin/sqlplus -s /NOLOG <<END
    set feedback off
    connect $CONNECT_ARS
    @"$OUTFILE"
    commit;
    exit;
END
    return 0
}

srvlist=`get_hosts --os=Unix --control=YES`
INF "count hosts: `echo $srvlist | wc -w`"

put_file="$PRJDIR/local.hdd.sh"
#badsrvlist="tjk-ccboweb1"
ssh_command="./local.hdd.sh; rm ./local.hdd.sh"

for host in $srvlist
do
    echo $badsrvlist | sed 's/^/ /;s/$/ /' | grep " $host " > /dev/null;
    if [ "$?" == "0" ]; then
	INF "host $host in badsrvlist (STUPID SERVER!)"
	continue
    fi
    (
    sftp $user@$host &> /dev/null << END
put $put_file
END
    #server_info=`ssh $user@$host "$ssh_command"` 
    SSH $user@$host "$ssh_command" server_info
	[ -z "$server_info" ] && continue
	real_host=`echo "$server_info" | awk -F":" '{print $1}'`
	os_version=`echo "$server_info" | awk -F":" '{print $2}'`
	server_model=`echo "$server_info" | awk -F":" '{print $3}'`    
	cpu=`echo "$server_info" | awk -F":" '{print $4}'`
	sn=`echo "$server_info" | awk -F":" '{print $5}'`
	ram=`echo "$server_info" | awk -F":" '{print $6}'`
	internal_hdd=`echo "$server_info" | awk -F":" '{print $7}'`
    
	[ -z "$real_host" ] && ERR "not get REAL_HOST information from $host"
	[ -z "$os_version" ] && ERR "not get OS_VERSION information from $host"
	[ -z "$server_model" ] && ERR "not get SERVER_MODEL information from $host"
	[ -z "$cpu" ] && ERR "not get CPU information from $host"
	[ -z "$sn" ] && ERR "not get SN information from $host"
	[ -z "$internal_hdd" ] && ERR "not get HDD information from $host"
	[ -z "$ram" ] && ERR "not get RAM information from $host"

	echo "update hosts_profile set real_host=trim('$real_host'), os_version=trim('$os_version'), \
server_model=trim('$server_model'), \
cpu=trim('$cpu'), sn=trim('$sn'), internal_hdd=trim('$internal_hdd'), ram=trim('$ram') where host='$host';" >> $OUTFILE
    
    ) &
done
WAIT 180

update_db
if [ "$?" -ne 0 ]; then
    ERR "error function update_db()"
    exit 1
fi

exit 0
